import 'package:flutter/cupertino.dart';
import 'package:flutter_gromore_ads/event/ad_ecpm_event.dart';
import 'package:flutter_gromore_ads/event/ad_error_event.dart';
import 'package:flutter_gromore_ads/event/ad_event_action.dart';
import 'package:flutter_gromore_ads/event/ad_reward_event.dart';
import 'package:flutter_gromore_ads/flutter_gromore_ads.dart';
import '../../../../utils/k_log.dart';
import '../../ads/ads_const.dart';
import '../../ads/ads_utils.dart';
import '../../api/api_service.dart';
import '../../event_bus/event_bus_utils.dart';
import 'ads_service.dart';

// class AdsServiceImpl implements AdsService {
//   @override
//   Future<bool> initAd(String appId) async {
//     return false;
//   }
//
//   @override
//   Future<bool> launchTestTools() async{
//     return false;
//   }
//
//   @override
//   Future<Widget> loadFeedAd(String posId, {double width = 375, double height = 400, int count = 1, bool isDraw = false, bool autoResize = true, bool show = false}) async{
//     return const SizedBox();
//   }
//
//   @override
//   void onEventListener() {
//   }
//
//   @override
//   Future<bool> preloadInsertPosids(List<String> posIds) async{
//     return false;
//   }
//
//   @override
//   Future<bool> preloadRewardPosids(List<String> posIds) async{
//     return false;
//   }
//
//   @override
//   Future<bool> requestIDFA() async{
//     return false;
//   }
//
//   @override
//   Future<bool> showInterstitialAd(String posId) async{
//     return false;
//   }
//
//   @override
//   Future<bool> showRewardVideoAd(String posId)async {
//     return false;
//   }
//
//   @override
//   Future<bool> showSplashAd(String posId)async {
//     return false;
//   }
//
// }



class AdsServiceImpl implements AdsService {
  //初始化广告
  @override
  Future<bool> initAd(String appId) async {
    try {
      return await FlutterGromoreAds.initAd(
        appId,
        useMediation: true,
        themeStatus: 0,
        isLocation: false,
        isOaid: false,
        isAndroidId: false,
        isPhoneState: false,
        isAlist: false,
      );
    } catch (e) {
      return false;
    }
  }


  @override
  Future<bool> launchTestTools() async {
    return await FlutterGromoreAds.launchTestTools();
  }

  @override
  Future<bool> showSplashAd(String posId) async {
    return await FlutterGromoreAds.showSplashAd(posId);
  }

  @override
  Future<Widget> loadFeedAd(
    String posId, {
    double width = 375,
    double height = 400,
    int count = 1,
    bool isDraw = false,
    bool autoResize = true,
    bool show = false,
  }) async {
    if (!show) {
      return const SizedBox();
    }

    var feedAd = await FlutterGromoreAds.loadFeedAd(
      posId,
      count: count,
    );

    if (feedAd.isEmpty) {
      return const SizedBox();
    }

    return AdFeedWidget(
      posId: feedAd[0].toString(),
      width: width,
      height: height,
      autoResize: autoResize,
      show: show,
    );
  }

  @override
  Future<bool> showInterstitialAd(String posId) async {
    return await FlutterGromoreAds.showInterstitialAd(posId);
  }

  @override
  Future<bool> showRewardVideoAd(String posId) async {
    return FlutterGromoreAds.showRewardVideoAd(posId);
  }

  @override
  Future<bool> preloadRewardPosids(List<String> posIds) async {
    return await FlutterGromoreAds.preload(rewardPosids: posIds,concurrent: 4);
  }

  @override
  Future<bool> preloadInsertPosids(List<String> posIds) async {
    return await FlutterGromoreAds.preload(insertPosids: posIds,concurrent: 4);
  }

  @override
  Future<bool> requestIDFA() async {
    return await FlutterGromoreAds.requestIDFA;
  }

  @override
  void onEventListener() {
    FlutterGromoreAds.onEventListener(
      (event) async {
        KLog.d(
            'onEventListener ${event.adId}  adId:${event.adId} action:${event.action}');

        //开屏通知
        if (AdsConst.kpList.contains(event.adId)) {
          if (event.action == AdEventAction.onAdClosed ||
              event.action == AdEventAction.onAdSkip ||
              event.action == AdEventAction.onAdError) {
            eventBusUtils.kpSucceedEmit();
          }
        }

        //激励视频通知
        if (AdsConst.jlspnList.contains(event.adId)) {
          if (event.action == AdEventAction.onAdClosed ||
              event.action == AdEventAction.onAdSkip ||
              event.action == AdEventAction.onAdError) {
            eventBusUtils.jlspSucceedEmit();
          }
        }

        //插屏通知
        if (AdsConst.cpList.contains(event.adId)) {
          if (event.action == AdEventAction.onAdClosed ||
              event.action == AdEventAction.onAdSkip ||
              event.action == AdEventAction.onAdError) {
            eventBusUtils.cpSucceedEmit();
            eventBusUtils.cpSucceedEmitTow2();
          }
        }

        bool isXxl = AdsConst.getAdStyle(event.adId) == 0;
        String adId = event.adId;
        //信息流处理
        if (isXxl &&
            AdsUtils.posId.isNotEmpty &&
            !AdsConst.xxlList.contains(event.adId)) {
          adId = AdsUtils.posId;
        }

        if (event is AdErrorEvent) {
          //错误事件
        } else if (event is AdRewardEvent) {
          //激励事件
        } else if (event.action == AdEventAction.onAdLoaded) {
          //请求
          if (isXxl) {
            AdsUtils.posId = event.adId;
          }
          // ApiService().appReport(
          //   actionType: AdsConst.actionType2,
          //   adId: "",
          //   placementId: event.adId,
          //   adStyle: AdsConst.getAdStyle(event.adId),
          // );

        } else if (event.action == AdEventAction.onAdPresent) {

          //请求成功
          ApiService().appReport(
            actionType: AdsConst.actionType3,
            adId: "",
            placementId: adId,
            adStyle: AdsConst.getAdStyle(adId),
          );
        } else if (event is AdEcpmEvent) {
          //广告价格信息事件
          KLog.d(
            '行为上报 AdEcpmEvent '
            'adId: ${event.adId} '
            'slotId: ${event.slotId} '
            'ecpm: ${event.ecpm} '
            'channel: ${event.channel} '
            'subChannel: ${event.subChannel} '
            'sdkName: ${event.sdkName} '
            'scenarioId: ${event.scenarioId} '
            'showTime: ${event.showTime.toString()} '
            'clickTime: ${event.clickTime.toString()} ',
          );

          //临时附值
          AdsUtils.adEcpmEventData[adId] = {
            "sdkName": event.sdkName ?? '',
            "scenarioId": event.scenarioId ?? '',
            "ecpm": event.ecpm ?? '',
            "channel": event.channel ?? '',
            "subChannel": event.subChannel ?? '',
            "adId": adId ?? '',
            "slotId": event.slotId ?? '',
            "showTime": event.showTime.toString(),
            "clickTime": event.clickTime.toString(),
          };

          ///上报
          ApiService().appReport(
            //请求成功
            actionType: AdsConst.actionType0,
            adId: event.slotId ?? "",
            placementId: adId,
            adStyle: AdsConst.getAdStyle(adId),
            ecpm: event.ecpm,
            adPlatForm: AdsConst.getAdPlatformType(
                event.sdkName ?? event.channel ?? ""),
          );
        } else if (event.action == AdEventAction.onAdClicked) {
          //广告点击
          KLog.d('行为上报 onAdClicked');

          ///上报
          ApiService().appReport(
            //点击
            actionType: AdsConst.actionType1,
            adId: AdsUtils.adEcpmEventData[adId]?["slotId"] ?? "",
            placementId: adId,
            adStyle: AdsConst.getAdStyle(adId),
            ecpm: AdsUtils.adEcpmEventData[adId]?["ecpm"] ?? "",
            adPlatForm: AdsConst.getAdPlatformType(
                AdsUtils.adEcpmEventData[adId]?["sdkName"].toString() ??
                    ""),
          );
        }
      },
    );
  }
}
